package com.springfreemwork;

import com.alibaba.fastjson.JSON;
import com.springframework.context.utils.ScanUtils;
import com.springframework.factory.BeanFactory;
import com.springframework.factory.support.ContainerFactory;
import com.springfreemwork.annotation.Properties;
import com.springfreemwork.properties.ServerProperties;
import com.springfreemwork.tomcat.servlet.DefaultServletHandler;
import com.springfreemwork.tomcat.EmbeddedTomcatServer;
import com.springfreemwork.tomcat.ServletHandler;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author gpo12345678@163.com
 * @create 2024-04-01 18:19
 */
public class SpringApplication {

	public static BeanFactory run(Class<?> primarySource) {
		String name = primarySource.getName();
		String[] split = name.split("\\.");
		split[split.length-1] = "";
		String packages = String.join(".", split);
		if(packages.endsWith(".")){
			packages = packages.substring(0,packages.length()-1);
		}
		List<Class<?>> classes = ScanUtils.scan(packages);
		List<Class<?>> classesBase = ScanUtils.scan("com.springfreemwork");
		BeanFactory containerFactory = new ContainerFactory(classes);
		loadProperties(containerFactory, classes);
		loadProperties(containerFactory, classesBase);
		ServerProperties serverProperties = containerFactory.getBean(ServerProperties.class);
		ServletHandler servletHandler = new DefaultServletHandler();
		EmbeddedTomcatServer embeddedTomcatServer = new EmbeddedTomcatServer(serverProperties,servletHandler.servletMapping(classes));
		embeddedTomcatServer.run();
		return containerFactory;
	}


	private static void loadProperties(BeanFactory containerFactory,List<Class<?>> classes){

		InputStream inputStream = SpringApplication.class.getResourceAsStream("/application.yml");
		Yaml yaml = new Yaml();
		Map<String, Object> data = yaml.load(inputStream);
		for (Class<?> aClass : classes) {
			if(aClass.isAnnotationPresent(Properties.class)){
				String prefix = aClass.getAnnotation(Properties.class).prefix();
				Object o1 = data.get(prefix);
				Object o2 = JSON.parseObject(JSON.toJSONString(o1), aClass);
				containerFactory.setBean(aClass.getName(),o2);
			}
		}

	}





}
